package parser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import data.Waypoint;

public class ParsingHelper {

	private String path;
	
	public List<Waypoint> parseGpxFile(String filePath) 		
			throws ParseException {
  		this.path = filePath;
		System.out.println(filePath);
		Parser parser = new Parser(path);
		Document gpxDoc;

		Double latitude;
		Double longitude;
		Double name = 0.0;
		String time = "";
		
		gpxDoc = parser.parse();
		
		NodeList gpxElements = gpxDoc.getElementsByTagName("gpx");
		// There is only one gpx element in the file
		//TODO schoen machen
		//if (gpxElements.getLength() > 0) {
		Element gpxData = (Element) gpxElements.item(0);



		NodeList waypointsXml = gpxData.getElementsByTagName("wpt");
		
		//There is only one gpx element in the file
		
		ArrayList<Waypoint> waypoints = new ArrayList<Waypoint>( waypointsXml.getLength() );
		int lenght =  waypointsXml.getLength();

		for (int i = 0; i < lenght; i++ ) {			
			Element gpxElement = (Element) waypointsXml.item(i);
			latitude = Double.parseDouble( gpxElement.getAttribute("lat") );
			longitude = Double.parseDouble( gpxElement.getAttribute("lon") );
			
			NodeList timeNode = gpxElement.getElementsByTagName("time");
			// only one time element exits
			if (timeNode.getLength() > 0) {
				Element timeElement = (Element) timeNode.item(0);
				time = timeElement.getTextContent();
			}
			
			NodeList nameNode = gpxElement.getElementsByTagName("name");
			// only one time element exits
			if (nameNode.getLength() > 0) {
				Element nameElement = (Element) nameNode.item(0);
				name = Double.parseDouble(nameElement.getTextContent());
			}
			
			//TODO checken wann sich erzeugen lohnt
			Waypoint wpt = new Waypoint(latitude, longitude, time, name);
//			Waypoint wpt = new Waypoint();			
			waypoints.add(wpt);
		} 
		return waypoints;
		//TODO rueckmeldung ueber erfolg
	}
}
